const fs = require('fs');
const path = require('path');
const gulp = require('gulp');
const del = require('del');
const uglify = require('gulp-uglify');
const rename = require("gulp-rename");
const cleanCSS = require('gulp-clean-css');
const copy = require('gulp-copy');

gulp.task("clean", async () => {
  console.log('----开始清理dist-min----')
  await del(['dist-min/**/*']);
})


gulp.task("copy", async () => {
  console.log('----拷贝三方插件----')
  await gulp.src(['dist/third-party/**/*'])
    .pipe(gulp.dest('dist-min/third-party'));

  console.log('----拷贝html----')
  await gulp
    .src(['dist/**/*.html'])
    .pipe(gulp.dest('dist-min'));
})

gulp.task('imagecopy', async () => {
  console.log('----拷贝图片----')
  await copyImages('dist', 'dist-min');
})


gulp.task("uglify", async () => {
  console.log('----开始压缩js----')
  await gulp
    .src(["dist/**/*.js", "!dist/third-party/**/*.js"])
    .pipe(uglify())//压缩文件
    .pipe(rename({
      suffix: ".min"
    }))
    .pipe(gulp.dest("dist-min"))
})

gulp.task("cssmin", async () => {
  console.log('----开始压缩css----')
  await gulp
    .src(['dist/**/*.css', '!dist/third-party/**/*.css'])
    .pipe(cleanCSS())
    .pipe(gulp.dest('dist-min'));
})


gulp.task("default", gulp.series('clean', 'copy', 'imagecopy', gulp.parallel('uglify', 'cssmin')));



function copyImages(source, destination) {
  // 读取source路径下的内容
  fs.readdir(source, (err, files) => {
    if (err) {
      console.error('Error reading the directory', err);
      return;
    }
    // 对每个文件进行处理
    files.forEach(file => {
      const sourcePath = path.join(source, file);
      const destinationPath = path.join(destination, file);
      // 获取文件的状态
      fs.stat(sourcePath, (err, stats) => {
        if (err) {
          console.error('Error getting stats', err);
          return;
        }
        // 如果是文件夹，则递归调用copyImages
        if (stats.isDirectory()) {
          fs.mkdir(destinationPath, { recursive: true }, err => {
            if (err) {
              console.error('Error creating directory', err);
              return;
            }
            copyImages(sourcePath, destinationPath);
          });
        } else if (/\.(jpg|jpeg|png|gif|svg)$/i.test(file)) { // 检查是否为图片文件
          // 如果是图片文件，则复制文件
          fs.copyFile(sourcePath, destinationPath, err => {
            if (err) {
              console.error('Error copying file', err);
              return;
            }
          });
        }
      });
    });
  });
}

